/**
 * Copyright (c) 2010 Basil Shikin, LegoCamera Project
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package org.legocam;

import java.util.Random;

import lejos.nxt.ColorLightSensor;


/**
 * This class contains utilities for timing values 
 * 
 * @author Basil Shikin
 *
 */
public class ExposureUtils
{
	// This array contains mapping of EV (array index) to Lego sensor reading (array value)
	//  	  	  	  	  	  	  	  	  	  	  	  0   1   2   3   4    5    6    7    8    9    10   11   12   13    14   	
	private static final int[] evValues = new int[] { 60, 70, 80, 90, 140, 290, 360, 390, 530, 690, 830, 900, 930, 1000, 1020};
	
	public static final int LIGHT_MEASURE_SAMPLES = 6;
	
	/**
	 * Convert lego color sensor reading into EV
	 * 
	 * @param rawValue Raw sensor reading
	 * 
	 * @return EV
	 */
	public static int getEVValue( final int rawValue )
	{
		int ev = 0;
		
		while ( ev < evValues.length && rawValue > evValues[ ev ] )
		{
			ev += 1;
		}
		
		return ev;
	}
	
	/**
	 * Calculate shutter time for given EV, f-Stop and ISO
	 * 
	 * @param ev  Current EV
	 * @param fStop Current aperture
	 * @param isoValue Film ISO
	 * 
	 * @return Time to keep shutter open (in seconds)
	 */
	public static double calculateShutterTime( final int ev, final int fStop, final int isoValue )
	{
		final double top = fStop*fStop * 100;
		final double bottom = Math.pow( 2, ev ) * isoValue;
		
		return top/bottom;
	}
	
	/**
	 * Read current light value
	 * @param lightSensor Sensor to read value from
	 * 
	 * @return Current raw light value
	 */
	public static int readLightValue( ColorLightSensor lightSensor)
	{
		// We need to read several light values then average the result
		final int[] values = new int[ LIGHT_MEASURE_SAMPLES ];
		final float[] weights = new float[ values.length ];
		final Random random = new Random();
		
		int averageTotal = 0;
		for ( int i = 0; i < values.length; i++ )
		{
			values[i] = lightSensor.readRawValue();
			averageTotal += values[i];
			
			try
			{
				// Sleep for a little bit before taking next measurement. Wait
				// random number of seconds, but make sure not to take more then
				// 600ms totoal
				Thread.sleep( random.nextInt( 600/values.length ) );
			}
			catch (InterruptedException e) {} 
		}
		
		int averageValue = averageTotal/values.length;
		
		// Distribute weights: we want higher values have a little
		// more weight
		for ( int i = 0; i < values.length; i++ )
		{
			weights[i] = values[i] > averageValue ? 1.5F : 1.0F;
		}
		
		float resultTop = 0;
		float resultBottom = 0;
		
		for ( int i = 0; i < values.length; i++ )
		{
			resultTop += values[i]*weights[i];
			resultBottom += weights[i];
		}
		
		return Math.round( resultTop / resultBottom );
	}
}
